﻿using Modbus.Device;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using z05_winform;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolBar;

namespace ClassStyle
{
    public partial class Form1 : Form
    {
        public static PLCAction plc;

        string basepath = Application.StartupPath;//获取应用程序的启动路径
        public PLCAction Plc { get; set; }
        public Form1(PLCAction plc) : this()
        {
            Plc = plc;
        }
        string plcInfo = "PLC信息";
        string classAddAddress = "DB10.1";//班级增加
        string classDeleteAddress = "DB10.5";//班级删除
        string classUpdateAddress = "DB10.9";//班级修改
        string studentAddAddress = "DB10.11";//学生增加
        string studentDeleteAddress = "DB10.15";//学生删除
        string studentUpdateAddress = "DB10.19";//学生修改
        public Form1()
        {
            InitializeComponent();//初始化控件
            
            Control.CheckForIllegalCrossThreadCalls = false;//跨线程访问

            plc = new PLCAction(Application.StartupPath);//将路径存储在PLCAction里
            plc.Exec();//启动心跳
            FileHelper2025.TxtLog("开始初始化系统", this);
            //================================================================================================== 检查学生文件是否存在
            string filePath = basepath + "\\student.CSV";
            if (!File.Exists(filePath))
            {
                // 文件不存在，创建文件并写入表头
                using (FileStream fs = File.Create(filePath))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                    {
                        sw.WriteLine("班级号,学号,姓名,年龄");
                    }
                }
            }
            //================================================================================================== 检查班级文件是否存在
            string classFilePath = basepath + "\\class.ini";
            if (!File.Exists(classFilePath))
            {
                // 文件不存在，创建文件并写入表头
                using (FileStream fs = File.Create(classFilePath))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        Dictionary<string, string> dicss = FileHelper.GetKeyValuePairs(basepath + "\\class.ini", "班级信息");
                    }
                }
            }
            //==================================================================================================读取班级里的文件信息到dataGridView1表里
            GridViewHelper.AddColumns(dataGridView1, new string[] { "班级号", "描述" });
            //读取ini文件的数据
            Dictionary<string, string> dics = FileHelper.GetKeyValuePairs(basepath + "\\class.ini", "班级信息");
            //将数据放入到DataGridView里
            if (dics == null) return;
            foreach (KeyValuePair<string, string> item in dics)
            {
                GridViewHelper.AddRow(dataGridView1, new string[] { item.Key, item.Value });
            }
            //==================================================================================================读取学生里的文件信息到dataGridView2表里
            GridViewHelper.AddColumns(dataGridView2, new string[] { "班级号", "学号", "姓名", "性别" });
            //获取文件数据，导入到grid里
            List<string> list = FileHelper.Read_CSV(basepath + "\\student.CSV");
            //将数据 放入到grid里
            for (int i = 0; i < list.Count; i++)
            {
                GridViewHelper.AddRow(dataGridView2, new string[] { list[i].Split(',')[0], list[i].Split(',')[1], list[i].Split(',')[2], list[i].Split(',')[3] });
            }
            //==================================================================================================将所有的增删改操作放入Plc里
            this.Plc = Form1.plc;
            Plc.AddTemplete(new DataTemplete(classAddAddress, plcInfo, classAdd));//班级增加
            Plc.AddTemplete(new DataTemplete(classDeleteAddress, plcInfo, classDelete));//班级删除
            Plc.AddTemplete(new DataTemplete(classUpdateAddress, plcInfo, classUpdate));//班级修改

            Plc.AddTemplete(new DataTemplete(studentAddAddress, plcInfo, studentAdd));//学生增加
            Plc.AddTemplete(new DataTemplete(studentDeleteAddress, plcInfo, studentDelete));//学生删除
            Plc.AddTemplete(new DataTemplete(studentUpdateAddress, plcInfo, studentUpdate));//学生修改
        }

        // 创建一个新的线程，并指定堆栈大小
        private void classReset()//班级重置
        {
            textBox1.Text = "";
            textBox2.Text = "";
        }
        private void button1_Click(object sender, EventArgs e)//班级增加
        {
           
            MessageBox.Show("班级增加");
            //FileHelper2025.Set_ini_data(plcInfo, classAddAddress, "true", basepath + "\\plc.ini");
            ModbusHelper.Instance.Set_modbus_data(0,true);
        }
        public void classAdd()//班级增加方法
        {
            ModbusHelper.Instance.Set_modbus_data(0, false);

            FileHelper.Set_ini_data("班级信息", textBox1.Text, textBox2.Text, basepath + "\\class.ini");
            GridViewHelper.AddRow(dataGridView1, new string[] { textBox1.Text, textBox2.Text });
            classReset();

            FileHelper2025.TxtLog("进行班级增加操作", this);
            //FileHelper2025.Set_ini_data(plcInfo, classAddAddress, "false", basepath + "\\plc.ini");

           
        }
        private void button2_Click(object sender, EventArgs e)//班级删除
        {
            MessageBox.Show("班级删除");
            //FileHelper2025.Set_ini_data(plcInfo, classDeleteAddress, "true", basepath + "\\plc.ini");
           
        }
        public void classDelete() //班级删除方法
        {
            //删除选中的行
            int index = GridViewHelper.GetSelectedRowIndex(dataGridView1);
            //删除获取行的那个编号
            string[] arr = GridViewHelper.GetRowsData(dataGridView1, index);
            string delId = arr[0];

            GridViewHelper.RemoveRowAtIndex(dataGridView1, index);
            //将数据同步到文件里
            FileHelper2025.Set_ini_data("班级信息", delId, null, basepath + "\\class.ini");
            FileHelper2025.TxtLog("进行班级删除操作", this);

            //FileHelper2025.Set_ini_data(plcInfo, classDeleteAddress, "false", basepath + "\\plc.ini");
        }
        private void button6_Click(object sender, EventArgs e)//班级修改
        {
            MessageBox.Show("班级修改");
            //FileHelper2025.Set_ini_data(plcInfo, classUpdateAddress, "true", basepath + "\\plc.ini");
           
        }
        public void classUpdate()//班级修改方法
        {
            int index = GridViewHelper.GetSelectedRowIndex(dataGridView1);
            string[] arr = GridViewHelper.GetRowsData(dataGridView1, index);
            GridViewHelper.UpdateRowsAtIndex(dataGridView1, new string[] { textBox1.Text, textBox2.Text }, index);
            FileHelper2025.Set_ini_data("班级信息", arr[0], null, basepath + "\\class.ini");
            FileHelper2025.Set_ini_data("班级信息", textBox1.Text, textBox2.Text, basepath + "\\class.ini");

            FileHelper2025.TxtLog("进行班级修改操作", this);
            //FileHelper2025.Set_ini_data(plcInfo, classUpdateAddress, "false", basepath + "\\plc.ini");

           
        }
        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            int index = e.RowIndex;
            //if (index <= 0) return;
            string[] arr = GridViewHelper.GetRowsData(dataGridView1, index);
            //将数据放入到框框里
            textBox1.Text = arr[0];
            textBox2.Text = arr[1];

        }
        public void verify(out int index) //班级校验
        {
            index = 0;
            Dictionary<string, string> kvs = FileHelper.GetKeyValuePairs(basepath + "\\class.ini", "班级信息");
            foreach (KeyValuePair<string, string> item in kvs)
            {
                string key = item.Key;
                if ("班级号：" + textBox5.Text == key + "")
                {
                    index = -1;
                }
            }
        }
        //========================================================================================================================================================================================
        public void studentVerify(out int studentndex)//学生校验
        {
            studentndex = 0;
            List<string> s = FileHelper.Read_CSV(basepath + "\\student.csv");
            string[] userInput = new string[] { textBox5.Text, textBox4.Text, textBox6.Text, textBox7.Text };
            foreach (string item in s)
            {
                string[] studentData = item.Split(','); // 将每行字符串拆分成数组
                if (studentData.Length == userInput.Length && studentData.SequenceEqual(userInput))
                {
                    studentndex = -1;
                    return; // 如果只需要找到第一个匹配项，找到后直接退出
                }
            }
        }
        public void studentReset() //学生重置
        {
            textBox5.Text = "";
            textBox4.Text = "";
            textBox6.Text = "";
            textBox7.Text = "";
        }
        private void button3_Click(object sender, EventArgs e)//学生增加
        {
           
            MessageBox.Show("学生增加");
           // FileHelper2025.Set_ini_data(plcInfo, studentAddAddress, "true", basepath + "\\plc.ini");
          
        }
        public void studentAdd() //学生增加方法
        {
            FileHelper.Write_CSV(new object[] { textBox5.Text, textBox4.Text, textBox6.Text, textBox7.Text }, new string[] { "班级号,学号,姓名,年龄" }, basepath, "student");
            GridViewHelper.AddRow(dataGridView2, new string[] { textBox5.Text, textBox4.Text, textBox6.Text, textBox7.Text });
            studentReset();

           // FileHelper2025.Set_ini_data(plcInfo, studentAddAddress, "false", basepath + "\\plc.ini");
        }
        private void button4_Click(object sender, EventArgs e)//学生删除
        {
           
            MessageBox.Show("学生删除");            
           // FileHelper2025.Set_ini_data(plcInfo, studentDeleteAddress, "true", basepath + "\\plc.ini");
           
        }
        public void studentDelete() //学生删除方法
        {
            studentVerify(out int studentIndex);
            if (studentIndex == 0)
            {
                MessageBox.Show("学号不存在！");
            }
            else
            {
                string filePath = basepath + "\\student.CSV";
                RemoveById(filePath, textBox4.Text);
                string[] arr = GridViewHelper.GetRowsData(dataGridView2, index);
                //删除数据
                GridViewHelper.RemoveRowAtIndex(dataGridView2, index);
            }
            //FileHelper2025.Set_ini_data(plcInfo, studentDeleteAddress, "false", basepath + "\\plc.ini");

        }
        public void RemoveById(string path, string id) //删除的方法
        {
            string studentIdToDelete = textBox4.Text; // 假设用户在textBox4中输入了要删除的学生的学号
            // 读取CSV文件内容到内存
            List<string[]> students = File.ReadAllLines(path)
                                          .Select(line => line.Split(','))
                                          .ToList();
            // 找到需要删除的行并移除
            students.RemoveAll(student => student[1].Trim() == studentIdToDelete); // 学号在第2列（索引为1）

            // 将修改后的数据写回到CSV文件
            using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8)) // false表示覆盖原有文件
            {
                foreach (string[] student in students)
                {
                    sw.WriteLine(string.Join(",", student));
                }
            }
        }
        int index;
        private void button5_Click(object sender, EventArgs e)//修改
        {
            MessageBox.Show("学生修改");            
           // FileHelper2025.Set_ini_data(plcInfo, studentUpdateAddress, "true", basepath + "\\plc.ini");
           
        }
        public void studentUpdate() //修改的方法
        {
            string oldId = GridViewHelper.GetRowsData(dataGridView2, index)[0];
            string classId = textBox5.Text;
            string studentId = textBox4.Text;
            string sex = textBox6.Text;
            string age = textBox7.Text;
            GridViewHelper.UpdateRowsAtIndex(dataGridView2, new string[] { classId, studentId, sex, age }, index);
            FileHelper2025.UpdateDataAtIndex(basepath + "\\student.CSV", new string[] { GridViewHelper.GetRowsData(dataGridView2, index)[0], oldId, GridViewHelper.GetRowsData(dataGridView2, index)[2], GridViewHelper.GetRowsData(dataGridView2, index)[3] }, new string[] { classId, studentId, sex, age });
            //FileHelper2025.Set_ini_data(plcInfo, studentUpdateAddress, "false", basepath + "\\plc.ini");
        }
        private void dataGridView2_RowEnter(object sender, DataGridViewCellEventArgs e)//选中行，把行的数据放入文本框里
        {
            index = e.RowIndex;
            string[] arr = GridViewHelper.GetRowsData(dataGridView2, index);
            textBox5.Text = arr[0];
            textBox4.Text = arr[1];
            textBox6.Text = arr[2];
            textBox7.Text = arr[3];
        }
        
        SerialPort serialPort;
        ModbusSerialMaster msm;
        bool isConnect = false;//是否连接
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = SerialPort.GetPortNames();//串口
            comboBox2.DataSource = new int[] { 1200, 2400, 4800, 9600, 14400, 19200 };//波特率
            comboBox2.SelectedIndex = 3;
            comboBox3.DataSource = Enum.GetNames(typeof(Parity));//校验位
            comboBox4.DataSource = new int[] { 7, 8 };//数据位
            comboBox4.SelectedIndex = 1;
            comboBox5.DataSource = Enum.GetNames(typeof(StopBits));//停止位
            comboBox5.SelectedIndex = 1;

            serialPort = new SerialPort();//创建串口对象
            radioButton1.Checked = true;
            toolStripStatusLabel1.Text = $"软件初始化成功!";
        }
        private void button7_Click(object sender, EventArgs e)//连接按钮
        {
            if (!serialPort.IsOpen)//！lfalse 就是true进入
            {
                serialPort.PortName = comboBox1.Text;
                serialPort.Open();//串口连接上
                isConnect = true;//把连接状态改成true
                if (radioButton1.Checked)
                {
                    msm = ModbusSerialMaster.CreateRtu(serialPort);
                }
                else if (radioButton2.Checked)
                {
                    msm = ModbusSerialMaster.CreateAscii(serialPort);
                }
                toolStripStatusLabel1.Text = $"串口{serialPort.PortName}连接";
            }
        }
        private void button8_Click(object sender, EventArgs e)//断开按钮
        {
            if (isConnect)
            {
                serialPort.Close();//关闭串口
                isConnect = false;//连接状态关闭
                toolStripStatusLabel1.Text = $"串口断开连接!";
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort != null && serialPort.IsOpen)
            {
                serialPort.Close();
            }
        }
        private void button9_Click(object sender, EventArgs e)
        {
            IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });
            using (TcpClient clinet = new TcpClient(address.ToString(), 502))
            {
                clinet.SendTimeout = 1;
                ModbusIpMaster master = ModbusIpMaster.CreateIp(clinet);

                ushort startAddress = 0;
                ushort numInputs = 5;
                bool[] inputs = master.ReadCoils(1, 0, 5);

                for (int i = 0; i < numInputs; i++)
                   MessageBox.Show($"Registers {(startAddress + i)}={(inputs[i])}");
            }
        }
    }
}
